Added ProtocolHelper and some tests
[brmtron.git] / BrmTron Server / src / cz / brmlab / brmtron / server / BrmTronServerThread.java
blob32bab9d1f7eecffdebb8e9791ce1aecc85f5a095
1 package cz.brmlab.brmtron.server;
3 import java.io.BufferedReader;
4 import java.io.DataOutputStream;
5 import java.io.InputStreamReader;
6 import java.net.Socket;
8 public class BrmTronServerThread extends Thread {
10 private Socket sock;
11 private int id;
12 private Player player;
15 public BrmTronServerThread(Socket sock, int id){
16 super("BrmTronServerThread");
17 this.sock = sock;
18 this.id = id;
19 this.player = new Player(id);
22 @Override
23 public void run() {
24 String s;
26 try {
27 DataOutputStream out = new DataOutputStream(sock.getOutputStream());
28 BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
30 player.setActive(true);
32 while((s=in.readLine()) != null) {
33 //debug commands
34 if(s.equalsIgnoreCase("die")){
35 player.setActive(false);
37 if(s.equals("quit")) {
38 break;
41 //parse client input
42 Player np = ProtocolHelper.parsePlayer(s);
43 player.merge(np);
45 PathElement elem = new PathElement(player.getPrevCoords(), player.getCoords());
47 //collision check
48 double[] tmp = BrmTronServer.checkForCollision(elem);
50 //add a wall; if player has crashed, change his end position to a crash location
51 if(tmp == null) {
52 BrmTronServer.addWall(elem);
53 } else {
54 elem.setEnd(tmp[0], tmp[1]);
55 BrmTronServer.addWall(elem);
56 player.setActive(false);
57 player.setCoords(tmp[0], tmp[1]);
60 //save player state and send him an update
61 BrmTronServer.updatePlayer(id, player);
62 out.writeBytes(ProtocolHelper.getUpdate(BrmTronServer.getPlayers()));
65 out.close();
66 in.close();
67 sock.close();
68 } catch(Exception e) {
69 System.err.println(e);